package org.chen.flight.service.flight;

import lombok.extern.slf4j.Slf4j;
import org.chen.common.flight.OneWayFlightData;
import org.chen.common.flight.RoundTripFlightData;
import org.chen.common.flight.*;
import org.chen.common.flight.request.FlightSearchRequest;
import org.chen.common.flight.response.OneWayFlightSearchResponse;
import org.chen.common.flight.response.RoundTripFlightSearchResponse;
import org.chen.flight.mapper.OneWayFlightDataMapper;
import org.chen.flight.mapper.RoundTripFlightDataMapper;
import org.chen.flight.service.ExcelExportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 航班数据库服务
 * 支持单程和往返数据分别保存到不同的表
 */
@Service
@Slf4j
public class FlightDataService {

    @Autowired
    private OneWayFlightDataMapper oneWayFlightDataMapper;

    @Autowired
    private RoundTripFlightDataMapper roundTripFlightDataMapper;

    @Autowired
    private ExcelExportService excelExportService;

    /**
     * 保存单程航班数据到数据库
     */
    public List<OneWayFlightInfo> saveOneWayFlightsToDatabase(List<OneWayFlightInfo> flights, String transactionId, FlightSearchRequest request) {
        if (CollectionUtils.isEmpty(flights)) {
            return flights;
        }

//        List<OneWayFlightInfo> savedFlights = new ArrayList<>();
//
//        try {
//            String searchRoute = request.getDeparture().toUpperCase() + "-" + request.getDestination().toUpperCase();
//            int savedCount = 0;
//            int duplicateCount = 0;
//
//            for (OneWayFlightInfo flight : flights) {
//                try {
//
//                    // 转换为数据库实体
//                    OneWayFlightData flightData = OneWayFlightData.fromOneWayFlightInfo(flight, transactionId, searchRoute);
//
//                    if (oneWayFlightDataMapper.existsByDataFingerprint(flightData.getDataFingerprint()) == 0) {
//                        oneWayFlightDataMapper.insert(flightData);
//                        // 设置生成的ID到原对象
//                        flight.setId(flightData.getId());
//                        savedFlights.add(flight);
//                        savedCount++;
//                    } else {
//                        duplicateCount++;
//                    }
//                } catch (Exception e) {
//                    log.warn("保存单个单程航班数据失败: {} - {}", flight.getFlightNumber(), e.getMessage());
//                }
//            }
//
//            log.info("单程航班数据保存完成 - 保存: {}, 重复跳过: {}, 总计: {}",
//                    savedCount, duplicateCount, flights.size());
        log.info("单程航班数据 - 总计: {}", flights.size());
//            return savedFlights;
            return flights;
//        } catch (Exception e) {
//            log.error("保存单程航班数据到数据库失败", e);
//            throw new RuntimeException("保存失败" + e.getMessage());
//        }
    }

    /**
     * 保存往返航班数据到数据库
     */
    public List<RoundTripFlightInfo> saveRoundTripFlightsToDatabase(List<RoundTripFlightInfo> flights, String transactionId, FlightSearchRequest request) {
        if (CollectionUtils.isEmpty(flights)) {
            return flights;
        }

//        List<RoundTripFlightInfo> savedFlights = new ArrayList<>();

//        try {
//            String searchRoute = request.getDeparture().toUpperCase() + "-" + request.getDestination().toUpperCase();
//            int savedCount = 0;
//            int duplicateCount = 0;

//            for (RoundTripFlightInfo flight : flights) {
//                try {
//                    RoundTripFlightData flightData = RoundTripFlightData.fromRoundTripFlightInfo(
//                            flight, transactionId, searchRoute);

//                    if (roundTripFlightDataMapper.existsByDataFingerprint(flightData.getDataFingerprint()) == 0) {
//                        roundTripFlightDataMapper.insert(flightData);
//                        // 设置生成的ID到原对象
//                        flight.setId(flightData.getId());
//                        savedFlights.add(flight);
//                        savedCount++;
//                    } else {
//                        duplicateCount++;
//                    }
//                    savedFlights.add(flight);
//                } catch (Exception e) {
//                    log.warn("保存单个往返航班数据失败: {} - {}", flight.getRouteDescription(), e.getMessage());
//                }
//            }

//            log.info("往返航班数据保存完成 - 保存: {}, 重复跳过: {}, 总计: {}",
//                    savedCount, duplicateCount, flights.size());
            log.info("往返航班数据 - 总计: {}", flights.size());
//            return savedFlights;
            return flights;
//        } catch (Exception e) {
//            log.error("保存往返航班数据到数据库失败", e);
//            throw new RuntimeException("保存失败" + e.getMessage());
//        }
    }

    /**
     * 导出单程搜索结果
     */
    public ByteArrayResource exportOneWaySearchResult(OneWayFlightSearchResponse response,
                                                      FlightSearchRequest request,
                                                      boolean exportLowestPriceOnly) {
        try {
            return excelExportService.exportOneWayToExcel(response, request, exportLowestPriceOnly);
        } catch (Exception e) {
            log.error("导出单程Excel失败", e);
            throw new RuntimeException("导出Excel失败: " + e.getMessage());
        }
    }

    /**
     * 导出往返搜索结果
     */
    public ByteArrayResource exportRoundTripSearchResult(RoundTripFlightSearchResponse response,
                                                         FlightSearchRequest request,
                                                         boolean exportLowestPriceOnly) {
        try {
            return excelExportService.exportRoundTripToExcel(response, request, exportLowestPriceOnly);
        } catch (Exception e) {
            log.error("导出往返Excel失败", e);
            throw new RuntimeException("导出Excel失败: " + e.getMessage());
        }
    }
}